var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var ejs = require('ejs');
var pageRouter = require('./routes/page');
var proxy = require('express-http-proxy');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var app = express();

// view engine setup
app.engine('html', ejs.__express);
app.engine('jade', require('jade').__express);

app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', pageRouter);

// 反向代理（这里把需要进行反代的路径配置到这里即可）
let opts = {
    preserveHostHdr: true,
    reqAsBuffer: true,
//转发之前触发该方法
    proxyReqPathResolver: function (req, res) {
        req.url = req.baseUrl + req.url;
        return require('url').parse(req.url).path;
    }
};

app.use('/api', proxy('https://www.doutula.com', opts));
app.use('/dish-api', proxy('http://218.94.23.35:9092', opts));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    console.error(err.stack);
    res.render('error');
});


module.exports = app;
